﻿using Client;
using Shared.Method;
using Shared.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ManageSystem.Dialog
{
    public partial class FormProductSnLog : Form
    {
        private PRODUCT_SN_LOG _snLogW = null;
        //private YCD_ORDER _order = null;
        private bool _finished = false;

        private readonly string DATA_DIR = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "DATA\\";//保存包装数据

        public FormProductSnLog(PRODUCT_SN_LOG logW, bool finished, bool canDist)
        {

            InitializeComponent();
            _snLogW = logW;
            //_order = order;
            _finished = finished;

            if (canDist == false)
            {
                this.buttonDist.Visible = false;
                this.buttonReuse.Visible = false;
            }
        }


        private void SetListView(PRODUCT_SN_LOG pRODUCT_SN_LOG)
        {
            if (pRODUCT_SN_LOG == null) return;
            ListViewItem item = new ListViewItem();

            item.Text = pRODUCT_SN_LOG.ID.ToString();
            item.SubItems.Add(pRODUCT_SN_LOG.ORDER_SN);
            item.SubItems.Add(pRODUCT_SN_LOG.LINE_ID.ToString());
            item.SubItems.Add(pRODUCT_SN_LOG.DIST_NUMBER.ToString());
            item.SubItems.Add(pRODUCT_SN_LOG.START_SN.ToString());
            item.SubItems.Add(pRODUCT_SN_LOG.END_SN.ToString());
            item.SubItems.Add(pRODUCT_SN_LOG.LOG_TIME.ToString());

            this.listViewProductSnLog.Items.Add(item);
        }

        private void FormProductSnLog_Load(object sender, EventArgs e)
        {
            if (_snLogW == null) Close();
            var selectLog = MethodWcf.SelectProductSnLogClient(_snLogW);
            if (selectLog.result)
            {
                for (int i = 0; i < selectLog.value.Count; i++)
                {
                    SetListView(selectLog.value[i]);
                }
            }

            //MAC回收与使用添加到系统中，将生成数据放到文本文档中
            ShowLiftMacCount();

            //Device_Data deviceW = new Device_Data();
            //deviceW.SetWhere(string.Format(" ORDER_SN='{0}' and ( SN is null or SN ='')", _snLogW.ORDER_SN));
            //var selectDevice = MethodWcf.SelectDeviceDataClient(deviceW);
            //if (selectDevice.result)
            //{
            //    for (int i = 0; i < selectDevice.value.Count; i++)
            //        this.richTextBoxMacList.AppendText(selectDevice.value[i].MACAddr + "\r\n");
            //}

            return;
            //设计将产品改为FINISH状态，是不需要的事情
        }
        /* MAC分配机制和回收机制
         * 在此处分配MAC地址，在信息检查和出厂检查处回收？
         * 还有回收按钮可以回收？
         * */
        private void buttonDist_Click(object sender, EventArgs e)
        {
            //获取MAC
            int allMac;
            if (int.TryParse(this.textBoxAllMac.Text, out allMac) == false) { MessageBox.Show("未能成功转换可分配的MAC"); return; }
            int distMac;
            if(int.TryParse(this.textBoxDistMac.Text,out distMac) == false) { MessageBox.Show("请输入正确的分配数量");return; }

            if (allMac < distMac) { MessageBox.Show("不能分配超过当时剩余总数的MAC地址");return; }

            //查询最近的distMac数量的device_data数据
            Device_Data deviceW = new Device_Data();
            string sql = string.Format(@"ID in( select top {0} ID from Modem.dbo.Device_Data where USED=0 and ORDER_SN='{1}' and (SN is null or SN=''))
update Modem.dbo.Device_Data set USED=1 
where ID in( select top {0} ID from Modem.dbo.Device_Data where USED=0 and ORDER_SN='{1}' and (SN is null or SN='')
)",distMac,_snLogW.ORDER_SN);
            deviceW.SetWhere(sql);
            var selectDevice = MethodWcf.SelectDeviceDataClient(deviceW);

            if (selectDevice.result)
            {
                MessageBox.Show(string.Format("成功分配{0}个MAC地址", selectDevice.value.Count));

                string dirPath = DATA_DIR + DateTime.Now.ToString("yyyyMM") + "\\" + DateTime.Now.ToString("dd") + "\\";
                string fileName = _snLogW.ORDER_SN + "_" + DateTime.Now.ToString("HHmmss") + ".txt";
                string macMsg = null;

                this.richTextBoxMacList.Clear();
                for (int i = 0; i < selectDevice.value.Count; i++)
                {
                    this.richTextBoxMacList.AppendText(selectDevice.value[i].MACAddr + "\r\n");
                    //保存分配记录到当前目录下
                    macMsg += selectDevice.value[i].MACAddr + "\t" + selectDevice.value[i].DeviceType + "\t" + selectDevice.value[i].HW_PROVINCE_NAME + "\t" + selectDevice.value[i].ProductCode + "\r\n";
                }

                //写日志到本地

                LogHelper.WriteLog(dirPath, fileName, macMsg);
            }
            else
            {
                MessageBox.Show("分配MAC地址失败");
            }

            ShowLiftMacCount();
        }

        private void buttonReuse_Click(object sender, EventArgs e)
        {
            Resuse();

            return;

//            int num1 = 0, num2 = 0, num3 = 0;

//            //查询未绑定的MAC
//            Device_Data deviceW = new Device_Data();
//            string sqlSelect = string.Format(@" ORDER_SN='{0}' and USED=1 and (SN is null or SN='') and MACAddr not in(
//select A.MACAddr from Modem.dbo.Device_Data AS A,TRCTL.dbo.PRODUCT AS B 
//where A.ORDER_SN='{0}' and A.USED=1 and (A.SN is null or A.SN='') AND A.MACAddr=B.MAC
//)", _snLogW.ORDER_SN);
//            deviceW.SetWhere(sqlSelect);
//            var selectDeviceCount = MethodWcf.SelectDeviceDataCountClient(deviceW);
//            if (selectDeviceCount.result)
//            {
//                num1=int.Parse(selectDeviceCount.message);
//            }

//            sqlSelect = @" MACAddr in(
//select A.MACAddr from Modem.dbo.Device_Data AS A,TRCTL.dbo.PRODUCT AS B 
//where A.ORDER_SN='{0}' and A.USED=1 and (A.SN is null or A.SN='') 
//AND A.MACAddr=B.MAC AND B.END_TIME<'{1}' and B.NODE_ID={2})
//";

//            //确定回收语音信息检三日前的MAC
//            deviceW.Clear();
//            deviceW.SetWhere(string.Format(sqlSelect, _snLogW.ORDER_SN, DateTime.Now.AddDays(-3).Date, 20081));
//            selectDeviceCount = MethodWcf.SelectDeviceDataCountClient(deviceW);
//            if (selectDeviceCount.result)
//            {
//                num2 = int.Parse(selectDeviceCount.message);
//            }

//            //确定回收出厂检15日前的MAC
//            deviceW.Clear();
//            deviceW.SetWhere(string.Format(sqlSelect, _snLogW.ORDER_SN, DateTime.Now.AddDays(-15).Date, 20078));
//            selectDeviceCount = MethodWcf.SelectDeviceDataCountClient(deviceW);
//            if (selectDeviceCount.result)
//            {
//                num3 = int.Parse(selectDeviceCount.message);
//            }

//            //展示可以回收的总数
//            MessageBox.Show(string.Format("可回收总数【{0}】\r\n未绑定MAC数【{1}】\r\n语音信息检MAC数【{2}】\r\n出厂检查MAC数【{3}】",num1+num2+num3,num1,num2,num3));

//            var result = MessageBox.Show(string.Format("是否回收数量为【{0}】的未绑定MAC地址", num1), "确定回收", MessageBoxButtons.YesNo);
//            if (result == DialogResult.No) return;

//            //回收所有未绑定的MAC
//            string sql = string.Format(@"update Modem.dbo.Device_Data set USED=0 
//where ORDER_SN='{0}' and USED=1 and (SN is null or SN='') and MACAddr not in(
//select A.MACAddr from Modem.dbo.Device_Data AS A,TRCTL.dbo.PRODUCT AS B 
//where A.ORDER_SN='{0}' and A.USED=1 and (A.SN is null or A.SN='') AND A.MACAddr=B.MAC
//)", _snLogW.ORDER_SN);

//            var recovery=MethodWcf.ExecuteSQLClient(sql);

//            MessageBox.Show("回收未绑定的MAC数量：" + recovery);


//            //更新PRODUCT的语句
//            string sql2 = @"update TRCTL.dbo.PRODUCT set MAC=null where MAC in(
//select A.MACAddr from Modem.dbo.Device_Data AS A,TRCTL.dbo.PRODUCT AS B 
//where A.ORDER_SN='{0}' and A.USED=1 and (A.SN is null or A.SN='') 
//AND A.MACAddr=B.MAC AND B.END_TIME<'{1}' and B.NODE_ID={2})
//";
//            //更新Device_Data的语句
//            string sql3 = @"update Modem.dbo.Device_Data set USED=0 where MACAddr in(
//select A.MACAddr from Modem.dbo.Device_Data AS A,TRCTL.dbo.PRODUCT AS B 
//where A.ORDER_SN='{0}' and A.USED=1 and (A.SN is null or A.SN='') 
//AND A.MACAddr=B.MAC AND B.END_TIME<'{1}' and B.NODE_ID={2})";

//            result = MessageBox.Show(string.Format("是否回收数量为【{0}】的语音信息检查的MAC地址", num2), "确定回收", MessageBoxButtons.YesNo);
//            if (result == DialogResult.No) return;

//            //回收在语音信息检查工位三天前的MAC地址
//            recovery = MethodWcf.ExecuteSQLClient(string.Format(sql3, _snLogW.ORDER_SN, DateTime.Now.AddDays(-3).Date, 20081));
//            recovery = MethodWcf.ExecuteSQLClient(string.Format(sql2, _snLogW.ORDER_SN, DateTime.Now.AddDays(-3).Date, 20081));

//            MessageBox.Show("回收语音信息工位的MAC数量：" + recovery);


//            result = MessageBox.Show(string.Format("是否回收数量为【{0}】的出厂检查的MAC地址", num3), "确定回收", MessageBoxButtons.YesNo);
//            if (result == DialogResult.No) return;

//            //回收出厂检查十五天前的MAC地址
//            recovery = MethodWcf.ExecuteSQLClient(string.Format(sql2, _snLogW.ORDER_SN, DateTime.Now.AddDays(-15).Date, 20078));
//            recovery = MethodWcf.ExecuteSQLClient(string.Format(sql3, _snLogW.ORDER_SN, DateTime.Now.AddDays(-15).Date, 20078));

//            MessageBox.Show("回收出厂检查工位的MAC数量：" + recovery);

//            ShowLiftMacCount();
        }

        private void Resuse()
        {
            int num1 = 0, num2 = 0;//未绑定数量；可回收数量；

            //查询未绑定的MAC
            Device_Data deviceW = new Device_Data();
            string sqlSelect = string.Format(@" ORDER_SN='{0}' and USED=1 and (SN is null or SN='') and MACAddr not in(
select A.MACAddr from Modem.dbo.Device_Data AS A,TRCTL.dbo.PRODUCT AS B 
where A.ORDER_SN='{0}' and A.USED=1 and (A.SN is null or A.SN='') AND A.MACAddr=B.MAC
)", _snLogW.ORDER_SN);
            deviceW.SetWhere(sqlSelect);
            var selectDeviceCount = MethodWcf.SelectDeviceDataCountClient(deviceW);
            if (selectDeviceCount.result)
            {
                num1 = int.Parse(selectDeviceCount.message);
            }

            //查询无SN数量
            sqlSelect = @" MACAddr in(
select A.MACAddr from Modem.dbo.Device_Data AS A,TRCTL.dbo.PRODUCT AS B 
where A.ORDER_SN='{0}' and A.USED=1 and (A.SN is null or A.SN='') 
AND A.MACAddr=B.MAC AND B.END_TIME<'{1}' and B.NODE_ID IN (20063,20064,20065,20068,20069,20081,20078,20079))
";

            //确定回收无SN的MAC地址
            deviceW.Clear();
            deviceW.SetWhere(string.Format(sqlSelect, _snLogW.ORDER_SN, DateTime.Now/*.AddDays(-3)*/.Date));
            selectDeviceCount = MethodWcf.SelectDeviceDataCountClient(deviceW);
            if (selectDeviceCount.result)
            {
                num2 = int.Parse(selectDeviceCount.message);
            }

            //展示可以回收的总数
            MessageBox.Show(string.Format("可回收总数【{0}】\r\n未绑定MAC数【{1}】\r\n无SN的MAC数【{2}】（一天前）", num1 + num2 , num1, num2));

            var result = MessageBox.Show(string.Format("是否回收数量为【{0}】的未绑定MAC地址", num1), "确定回收", MessageBoxButtons.YesNo);
            if (result == DialogResult.No) return;


            //回收所有未绑定的MAC
            string sql = string.Format(@"update Modem.dbo.Device_Data set USED=0 
where ORDER_SN='{0}' and USED=1 and (SN is null or SN='') and MACAddr not in(
select A.MACAddr from Modem.dbo.Device_Data AS A,TRCTL.dbo.PRODUCT AS B 
where A.ORDER_SN='{0}' and A.USED=1 and (A.SN is null or A.SN='') AND A.MACAddr=B.MAC
)", _snLogW.ORDER_SN);

            var recovery = MethodWcf.ExecuteSQLClient(sql);

            MessageBox.Show("回收未绑定的MAC数量：" + recovery);

            //更新PRODUCT的语句
            string sql2 = @"update TRCTL.dbo.PRODUCT set MAC=null where MAC in(
select A.MACAddr from Modem.dbo.Device_Data AS A,TRCTL.dbo.PRODUCT AS B 
where A.ORDER_SN='{0}' and A.USED=1 and (A.SN is null or A.SN='') 
AND A.MACAddr=B.MAC AND B.END_TIME<'{1}' and B.NODE_ID IN(20063,20064,20065,20068,20069,20081,20078,20079))
";

//            //更新Device_Data的语句
//            string sql3 = @"update Modem.dbo.Device_Data set USED=0 where MACAddr in(
//select A.MACAddr from Modem.dbo.Device_Data AS A,TRCTL.dbo.PRODUCT AS B 
//where A.ORDER_SN='{0}' and A.USED=1 and (A.SN is null or A.SN='') 
//AND A.MACAddr=B.MAC AND B.END_TIME<'{1}' and B.NODE_ID IN(20063,20064,20065,20068,20069,20081,20078,20079))";

            result = MessageBox.Show(string.Format("是否回收数量为【{0}】的无SN的MAC地址", num2), "确定回收", MessageBoxButtons.YesNo);
            if (result == DialogResult.No) return;

            //回收在语音信息检查工位三天前的MAC地址
            recovery = MethodWcf.ExecuteSQLClient(string.Format(sql2, _snLogW.ORDER_SN, DateTime.Now/*.AddDays(-3)*/.Date));
            //recovery = MethodWcf.ExecuteSQLClient(string.Format(sql3, _snLogW.ORDER_SN, DateTime.Now.AddDays(-3).Date));

            recovery = MethodWcf.ExecuteSQLClient(sql);

            MessageBox.Show("回收无SN的MAC数量：" + recovery);

            ShowLiftMacCount();
        }

        private void ShowLiftMacCount()
        {
            this.textBoxDistMac.Clear();

            //显示剩余MAC总数量
            Device_Data deviceW = new Device_Data();
            deviceW.SetWhere();
            deviceW.ORDER_SN = _snLogW.ORDER_SN;
            deviceW.USED = false;
            deviceW.SetWhere("(SN is null OR SN='')");
            var selectDeviceCount = MethodWcf.SelectDeviceDataCountClient(deviceW);
            if (selectDeviceCount.result)
            {
                this.textBoxAllMac.Text = selectDeviceCount.message;
            }
            else
            {
                MessageBox.Show("查询订单未分配MAC失败");
                Close();
            }
        }
    }
}
